package org.servlet;


import com.google.gson.Gson;
import org.commons.ResultDto;
import org.dao.UserDao;
import org.entity.User;
import org.imple.UserImple;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户注册
 */
@WebServlet("/register.do")
public class RegisterServlet extends BaseServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name") ;
        String pass = req.getParameter("pass") ;
        String sex = req.getParameter("sex") ;
        int age = Integer.parseInt(req.getParameter("age")) ;

        User u = new User() ;
        u.setName(name);
        u.setPass(pass);
        u.setSex(sex);
        u.setAge(age);

        UserDao dao = new UserImple() ;
        int r = dao.addUser(u) ;

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        PrintWriter out = resp.getWriter() ;

        String json = null ;

        if(r == 1){
            ResultDto resultDao = successJson(null,200,"注册成功!") ;
            json = new Gson().toJson(resultDao) ;
        }else{
            ResultDto resultDao = errorJson("注册失败！") ;
            json = new Gson().toJson(resultDao) ;
        }
        out.print(json);

        out.flush();
        out.close();
    }
}
